package study.designpattern.adapter.impl;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.List;
import java.io.BufferedInputStream;

import study.designpattern.adapter.LogFileOperateApi;
import study.designpattern.adapter.bean.LogModel;


/**
 * 实现对日志文件的操作
 * @author taowei20061122@163.com
 *
 */
public class LogFileOperate implements LogFileOperateApi {
	/**
	 * 日志文件名和路径
	 */
	private String logFilePathName = "./logs/Adapter.log";
	/**
	 * 构造方法，传入文件的路径和名称
	 * @param _logFilePathName
	 */
	public LogFileOperate(String _logFilePathName) {
		if (null != _logFilePathName && _logFilePathName.trim().length() > 0) {
			this.logFilePathName = _logFilePathName;
		}
	}
	
	@Override
	public List<LogModel> readLogFile() {
		List<LogModel> list = null;
		
		ObjectInputStream oin = null;
		
		File file = new File(logFilePathName);
		if (file.exists()) {
			try {
				oin = new ObjectInputStream(new BufferedInputStream(new FileInputStream(file)));
				list = (List<LogModel>) oin.readObject();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			} finally {
				try {
					if (oin != null) {
						oin.close();
					}
				} catch (IOException ioException) {
					ioException.printStackTrace();
				}

			}
		}
		return list;
	}

	@Override
	public void writeLogFile(List<LogModel> list) {
		File file = new File(logFilePathName);
		ObjectOutputStream out = null;
		
		try {
			out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
			out.writeObject(list);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (out != null) {
					out.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

}
